﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OPCAutomation;
using RivetProject.Model;
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RivetProject.DAL;
using System.Diagnostics.Eventing.Reader;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Windows;
using Windows.Devices.PointOfService;
using Npgsql.Replication;
using System.Windows.Controls;
using System.IO;
using MiniExcelLibs;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Net.Http;
using MESTest;


namespace RivetProject.ViewModels
{
    public partial class MainWindowViewModel : ObservableObject
    {
        

        [ObservableProperty]
        private int okCount;

        [ObservableProperty]
        private int ngCount;

        [ObservableProperty]
        private int totalCount;

        [ObservableProperty]
        private bool light;

        [ObservableProperty]
        private bool scanCompleted;

        [ObservableProperty]
        private bool runFlag;
        [ObservableProperty]
        private int maxPressure;

        [ObservableProperty]
        private int maintainPressure;

        [ObservableProperty]
        private double realLocation;

        [ObservableProperty]
        private string? barCode;


        [ObservableProperty]
        private string? productName;

        [ObservableProperty]
        private ObservableCollection<LogItem> logitems;

        [ObservableProperty]
        private ObservableCollection<Product>? products;

        [ObservableProperty]
        private bool nameChecked;

        [ObservableProperty]
        private bool startTimeChecked;

        [ObservableProperty]
        private bool stopTimeChecked;

        [ObservableProperty]
        private bool codeChecked;

        [ObservableProperty]
        private string selectedQueryName;

        [ObservableProperty]
        private DateTime startTime;

        [ObservableProperty]
        private DateTime stopTime;

        [ObservableProperty]
        private string codeText;

        [ObservableProperty]
        private List<Record> dataLists;

        [ObservableProperty]
        private int currentDotIndex;

        [ObservableProperty]
        private int dotCount;

        [ObservableProperty]
        private SystemSettings? settings;

        [ObservableProperty]
        private bool productRunningFlag;

        [ObservableProperty]
        private bool isOK;

        [ObservableProperty]
        private bool isNG;

        [ObservableProperty]
        private int max;

        [ObservableProperty]
        private int min;

        [ObservableProperty]
        private ObservableCollection<TaskDetail> taskInfos;

        [ObservableProperty]
        private TaskDetail? selectedTask;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(TaskQueryCommand))]
        private bool isTaskQuery = false;

        [ObservableProperty]
        private Record selectedRecord;

        OPCGroup oPCGroup;
        OPCGroups oPCGroups;
        OPCItem oPCItemLight, oPCItemScan;
        OPCItems oPCItems;
        OPCServer oPCServer;
        OPCBrowser oPCBrowser;
        private Product? selectedProduct;
        
        public SerialPort CodePort;

        private List<PressureData> pressureDatas;

        Record record =new Record();
        partial void OnProductNameChanged(string? value)
        {
            if (value!= null)
            {
                foreach (var item in Products)
                {
                    if (item.HMIName.Equals(value))
                    {
                        selectedProduct = item;
                        IsTaskQuery = selectedProduct.IsTask;
                        Log($"当前产品切换为：{selectedProduct?.Name}");
                        return;
                    }
                }

                Log($"产品切换失败：{value}不存在");
                //Log($"{Encoding.UTF8.GetBytes(value).ToString()}");
                //Log($"{Encoding.UTF8.GetBytes(Products[1].Name).ToString()}");
            }
            else
            {
                Log("产品名称为空");
            }
            
        }
        partial void OnProductRunningFlagChanged(bool value)
        {
            if (value)
            {
                ProductBegin();
            }
            else
            {
                ProductEnd();
            }
        }
        private bool  DataResultCheck(List<PressureData> data)
        {
            if (data != null&& data.Count == DotCount)
            {
                foreach (var item in data)
                {
                    if(item.DotStatus ==false)
                        return false;
                }
                return true;
            }

            return false;
        }

        private async void ProductEnd()
        {
            Log("收到M505下降沿信号，产品铆压结束");
            //记录数据到数据库
            try
            {
                record.ProductName = selectedProduct?.Name;
                record.DateTime = System.DateTime.Now;

                record.Content = JArray.FromObject(pressureDatas);
                record.EquipmentCode = Settings.EquipmentCode;
                record.ProcessType = selectedProduct.ProcessType;
                //record.ProductCode = BarCode;
                record.ProdTaskId = SelectedTask?.TaskId;
                record.MaterialCode = selectedProduct.MaterialCode;
            }
            catch(Exception ex)
            {
                Log(ex.Message);
            }
            ///复位时会得到Un状态,即使两次都OK，在结束状态以前设备故障，被复位后，也会记录Un
            //if (IsOK && !IsNG)
            //{
            //    record.Result = "OK";
            //}
            //else if (!IsOK && IsNG)
            //{
            //    record.Result = "NG";
            //}
            //else
            //{
            //    record.Result = "Un";
            //}

            record.Result = DataResultCheck(pressureDatas)?"OK":"NG";


            if (selectedProduct.IsMESReport)
            {
                ReportWorkMessage reportWorkMessage = new ReportWorkMessage();
                reportWorkMessage.EquipmentCode = Settings.EquipmentCode;
                reportWorkMessage.UserId = Settings.UserId;
                reportWorkMessage.TaskId = SelectedTask.TaskId;
                reportWorkMessage.ProductSerialNumberInfoList = new List<ProductSerialNumberInfoList>();
                ProductSerialNumberInfoList productSerialNumberInfoList = new ProductSerialNumberInfoList();
                productSerialNumberInfoList.ProductSerialNumber = record.ProductCode;
                productSerialNumberInfoList.Result = record.Result;
                productSerialNumberInfoList.Ext = JsonConvert.SerializeObject(record.Content);
                reportWorkMessage.ProductSerialNumberInfoList.Add(productSerialNumberInfoList);
                var jsonreport = JsonConvert.SerializeObject(reportWorkMessage);
                Log($"报工数据准备：{jsonreport}");
                try
                {
                    var result = await SendHttpPostAsync(Settings.UrlReportWork, jsonreport);
                    if (result != null)
                    {
                       
                        Log($"报工返回结果：{result}");
                        var reportWorkResult = JsonConvert.DeserializeObject<RecvMaterialMessage>(result);
                        if (reportWorkResult != null && reportWorkResult.Data!=null && reportWorkResult.Data[0].Success ==true)
                        { 
                            Log($"报工成功：{reportWorkResult.Data[0].Msg}");
                        }
                        else
                        {
                            Log($"报工失败：{reportWorkResult?.Data?[0].Msg}");
                        }
                    }
                    else
                    {
                        Log("报工返回数据为空");
                    }
                }
                catch(Exception ex)
                {
                    Log($"报工数据发送失败：{ex.Message}");
                }

            }
           //主动数据上传 
            if (selectedProduct.IsDataUpload)
            {
                var jsonUpdata = JsonConvert.SerializeObject(record);
                Log($"上传数据准备：{jsonUpdata}");
                try
                {
                    var updataMessage = await SendHttpPostAsync(Settings.UrlUploadData, jsonUpdata);

                    if (updataMessage != null)
                    {
                        Log($"数据上传返回结果：{updataMessage}");
                        var recvUpdata = JsonConvert.DeserializeObject<RecvUpdata>(updataMessage);
                        if (recvUpdata.Success == true)
                        {
                            record.Uploaded = true;
                            Log("数据上传成功");
                        }
                        
                    }
                    else
                    {

                        Log("数据上传返回数据为空");
                    }
                    
                }
                catch(Exception ex)
                {
                    Log($"上传数据失败：{ex.Message}");
                }
               
                
                


            }
            Log("数据库准备完毕");
                //插入数据库
            try
            {
                int x = SqlSugarHelper.Db.Insertable<Record>(record).ExecuteCommand();
                if (x > 0)
                {
                    Log($"数据插入成功");
                }
                else
                {
                    Log($"数据插入失败");
                }

            }
            catch (Exception ex)
            {
                logger.Error("数据库操作失败：" + ex.Message);
            }
            //清空二维码，准备下一次
            BarCode = "";
            CodePort.ReadExisting();
            pressureDatas.Clear();
            record = new Record();
        }

        private void ProductBegin()
        {
            record = new Record();

            pressureDatas = new List<PressureData>();
            record.ProductCode = barCode;
            Log("收到M505置位信号，产品铆压开始");
        }

        partial void OnRunFlagChanged(bool value)
        {

            if (value)
            {
                //测试开始
                TestBegin();
            }
            else
            {
                //测试结束
                TestEnd();
            }
        }

        private void TestEnd()
        {
            Log("收到M501复位信号，单点铆压结束");

            PressureData pd = new PressureData();




            pd.Id = CurrentDotIndex;
            pd.MaxPressure = MaxPressure;
            pd.MaintainPressure = MaintainPressure;
            pd.Max = Max;
            pd.Min = Min;
            if (IsOK && !IsNG)
            {
                pd.DotStatus = true;
            }

            else if (!IsOK && IsNG)
            {
                pd.DotStatus = false;
            }

            Log($"数据准备：铆点编号{pd.Id},铆点状态{pd.DotStatus},最大压力{pd.MaxPressure},保压压力{pd.MaintainPressure}，压力上限{pd.Max}，压力下限{pd.Min}");


            pressureDatas.Add(pd);


            Log("数据准备完成");
            //if(currentDotIndex >= dotCount)
            //{
            //    //测试结束
                

            //}
            //else
            //{
               
            //}


        }

        private void TestBegin()
        {
            Log("收到M501置位信号，单点铆压开始");
        }

        [RelayCommand]
        private void Lighttoggle()
        {
            // int[] serverhandls = new int[2] { 0, 4 };
            // Array serverHandlsArray = (Array)serverhandls;
            object values;
            if (Light)
            {
                values = 0;
            }
            else
            {
                values = 1;
            }

            //Array valuesArray = (Array)values;
            // Array writeErrors;
            // int cancelID;

            // oPCGroup.AsyncWrite(1,ref serverHandlsArray,ref valuesArray,out writeErrors,2020,out cancelID);
            //oPCGroup.AsyncWrite(1,ref serverHandlsArray,);

            //oPCItems.GetOPCItem(3).Write(values);

            //oPCItem.Write(values);
            oPCItemLight.Write(values);

            // logger.Info("ServerHandle:"+oPCItemLight.ServerHandle.ToString());
            // logger.Info("ClientHandle:"+oPCItemLight.ClientHandle.ToString());

        }

        private void OPCGroup_AsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors)
        {
            //
        }

        private static log4net.ILog logger = log4net.LogManager.GetLogger("MainLog");
        private static log4net.ILog settinglogger = log4net.LogManager.GetLogger("SettingLog");
        public MainWindowViewModel()
        {
            TaskInfos = new ObservableCollection<TaskDetail>();
            pressureDatas = new List<PressureData>();
            logitems = new ObservableCollection<LogItem>();
            

            StartTime = DateTime.Now;
            StopTime = DateTime.Now;
            oPCServer = new OPCServer();
            var opcServerlist = oPCServer.GetOPCServers();
            oPCServer.Connect("Kepware.KEPServerEX.V6");

            oPCBrowser = oPCServer.CreateBrowser();
            oPCBrowser.ShowBranches();
            oPCBrowser.ShowLeafs(true);
            

            oPCGroups = oPCServer.OPCGroups;
            oPCGroups.DefaultGroupDeadband = 0;
            oPCGroups.DefaultGroupIsActive = true;
            oPCGroups.DefaultGroupUpdateRate = 200;
            oPCGroup = oPCGroups.Add("myGroup");
            oPCGroup.IsActive = true;
            oPCGroup.IsSubscribed = true;
            oPCItems = oPCGroup.OPCItems;
            //opcItemID,ClientID,
            
            //Settings = new SystemSettings();

            //Products = new ObservableCollection<Product>();
            //Products.Add(new Product() { Name = "产品1", IdentyCode = "1234567890123", Length = 10 });
            //Products.Add(new Product() { Name = "产品2", IdentyCode = "1234567890124", Length = 12 });
            //Products.Add(new Product() { Name = "产品3", IdentyCode = "1234567890125", Length = 15 });
            try
            {
                string jsonString = File.ReadAllText("products.json");
                Products = JsonConvert.DeserializeObject<ObservableCollection<Product>>(jsonString);
            }
            catch (Exception ex)
            {
                Log($"产品信息文件加载失败：{ex.Message}");
            }
            try
            {
                string jsonString2 = File.ReadAllText("Settings.json");
                Settings = JsonConvert.DeserializeObject<SystemSettings>(jsonString2);
            }
            catch (Exception ex)
            {
                Log($"系统设置文件加载失败：{ex.Message}");
            }

            LoadSettings();

            
            try
            {
                CodePort = new SerialPort();
                CodePort.PortName = Settings?.ComName;
                CodePort.BaudRate = 9600;
                CodePort.Parity = Parity.None;
                CodePort.DataBits = 8;
                CodePort.StopBits = StopBits.One;
                CodePort.Open();
                CodePort.DataReceived += CodePort_DataReceived;
                Log("串口打开成功");
            }
            catch (Exception ex)
            {
                logger.Error("串口打开失败："+ex.ToString());
            }
            //oPCItems.AddItem("ModbusRTUSerial.设备 1.HD10", 1);//ok产量地址
            //oPCItems.AddItem("ModbusRTUSerial.设备 1.HD12", 2);//ng产量地址
            //oPCItems.AddItem("ModbusRTUSerial.设备 1.HD14", 3);//总产量地址
            //oPCItemLight = oPCItems.AddItem("ModbusRTUSerial.设备 1.HM70", 4);//照明开关地址
            oPCItems.AddItem("ModbusRTUSerial.设备 1.D60", 5);//最大压力
            oPCItems.AddItem("ModbusRTUSerial.设备 1.D34", 6);//保压压力
            oPCItemScan = oPCItems.AddItem("ModbusRTUSerial.设备 1.M500", 1);//扫码完成状态地址
            oPCItems.AddItem("ModbusRTUSerial.设备 1.M501", 8);//测试状态地址
            //oPCItems.AddItem("ModbusRTUSerial.设备 1.D50", 9); //实时位置
            oPCItems.AddItem("ModbusRTUSerial.设备 1.D230", 10);//名字
            oPCItems.AddItem("ModbusRTUSerial.设备 1.HD50", 11);//当前铆压次数
            oPCItems.AddItem("ModbusRTUSerial.设备 1.HD60", 12);//总的铆压次数
            oPCItems.AddItem("ModbusRTUSerial.设备 1.M505", 13);//产品运行周期标志位
            oPCItems.AddItem("ModbusRTUSerial.设备 1.M507", 14);//OK信号
            oPCItems.AddItem("ModbusRTUSerial.设备 1.M508", 15);//NG信号
            oPCItems.AddItem("ModbusRTUSerial.设备 1.HD116", 16);//压力上限
            oPCItems.AddItem("ModbusRTUSerial.设备 1.HD118", 17);//压力下限
            oPCGroup.DataChange += OPCGroup_DataChange;
            oPCGroup.AsyncWriteComplete += OPCGroup_AsyncWriteComplete;
            Log("OPC服务启动");

            Log("程序初始化完成");
            //logger.Info("程序初始化完成");
            //Record rr = new Record();
            //rr.Code = "123";
            //rr.TestTime = DateTime.Now;
            //rr.MaxPressure = 1200;
            //rr.MaintainPressure = 1300;
            //try
            //{
            //    int x = SqlSugarHelper.Db.Insertable<Record>(rr).ExecuteCommand();
            //    if (x > 0)
            //    {
            //        logger.Info("数据插入成功");
            //    }
            //    else
            //    {
            //        logger.Info("数据插入失败");
            //    }
            //}
            //catch (Exception ex)
            //{
            //    logger.Info("启动数据插入错误");
            //}
        }

        private void LoadSettings()
        {

            
        }

        private async void CodePort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(150);
            //runflag测试时置1
            try
            {
                if (ProductRunningFlag)
                {
                    
                    string str = CodePort.ReadExisting();
                    

                    Log("测试期间收到二维码：" + str);
                }
                else
                {
                   // Thread.Sleep(30);
                    BarCode = CodePort.ReadExisting();
                    //删除回车符
                    if (BarCode.Contains("\r"))
                    {
                        BarCode = BarCode.Substring(0, BarCode.IndexOf("\r"));
                    }
                    if (selectedProduct.Check(BarCode))
                    {
                        //收到二维码，判断，执行置位允许测试
                        //   record.ProductName = ProductName;

                        // record.ProductCode = BarCode;
                        Log("收到合法二维码：" + BarCode);
                        //置位
                        if (selectedProduct.IsMESLoad)
                        {
                            //进行过站检查，通过后进行置位
                            LoadMaterialMessage loadMaterialMessage = new LoadMaterialMessage();
                            if (selectedProduct.IsTask)
                            {
                                if (SelectedTask == null || SelectedTask.TaskId == "")
                                {
                                    MessageBox.Show("订单号为空，不能进行上料");
                                    Log("订单号为空，不能进行上料");
                                    return;
                                }
                                else
                                {
                                    loadMaterialMessage.TaskId = SelectedTask.TaskId;
                                }
                            }
                            else
                            {
                                loadMaterialMessage.TaskId = "0";
                            }
                            loadMaterialMessage.EquipmentCode = Settings.EquipmentCode;
                            loadMaterialMessage.UserId = Settings.UserId;
                            loadMaterialMessage.ProductSerialNumberList  = new List<string>() { BarCode};
                            var json = JsonConvert.SerializeObject(loadMaterialMessage);
                            Log($"上料发送报文：{json}");
                            try
                            {
                                var result = await SendHttpPostAsync(Settings.UrlLoadMaterial, json);
                                Log($"上料接收报文：{result}");
                                if (result != null)
                                {
                                    var recvMaterialMessage = JsonConvert.DeserializeObject<RecvMaterialMessage>(result);
                                    
                                    if (recvMaterialMessage.Data[0].Success)
                                    {
                                        //过站校验通过，允许置位
                                        Log($"二维码{recvMaterialMessage.Data[0].ProductSerialNumber}上料校验通过，允许置位");
                                        oPCItemScan.Write((object)1);
                                    }
                                    else
                                    {
                                        Log($"二维码{recvMaterialMessage.Data[0].ProductSerialNumber}上料校验失败:{recvMaterialMessage.Data[0].Msg}");
                                    }
                                }
                                
                            }
                            catch (Exception ex)
                            {
                                Log($"二维码:{BarCode}上料校验时时不成功:{ex.Message}");
                            }
                            
                        }
                        else
                        {
                            Log("置位");
                            oPCItemScan.Write((object)1);
                        }
                       
                       
                    }
                        
                    else
                        Log("收到非法二维码：" + BarCode);
                    
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }

        }

        private void OPCGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            // logger.Info("进入一次");
            for (int i = 1; i <= NumItems; i++)
            {
                
                 logger.Debug($"时间:{TimeStamps.GetValue(i)},通讯质量:{Qualities.GetValue(i)},值:{ItemValues.GetValue(i)},ClientID:{ClientHandles.GetValue(i)}");
               // if(Convert.ToInt32(Qualities.GetValue(i)) == 192)
                switch (ClientHandles.GetValue(i))
                {
                    //case 1:
                    //    OkCount = Convert.ToInt32(ItemValues.GetValue(i));
                       
                    //    break;
                    //case 2:
                    //    NgCount = Convert.ToInt32(ItemValues.GetValue(i));
                    //    break;
                    //case 3:
                    //    TotalCount = Convert.ToInt32(ItemValues.GetValue(i));
                    //    break;
                    //case 4:
                    //    Light = Convert.ToBoolean(ItemValues.GetValue(i));
                    ////    break;
                    case 5:
                        MaxPressure = Convert.ToInt32(ItemValues.GetValue(i));
                        break;
                    case 6:
                        MaintainPressure = Convert.ToInt32(ItemValues.GetValue(i));
                        break;

                    case 1:
                        ScanCompleted = Convert.ToBoolean(ItemValues.GetValue(i));
                        break;
                    case 8:
                        RunFlag = Convert.ToBoolean(ItemValues.GetValue(i));
                        break;
                    //case 9:
                    //    RealLocation = Convert.ToDouble(ItemValues.GetValue(i)) / 100;
                    //    break;
                    case 10:
                        ProductName = (string?)ItemValues.GetValue(i);
                        break;
                    case 11:
                        CurrentDotIndex = Convert.ToInt32(ItemValues.GetValue(i));
                        break;
                    case 12:
                        DotCount = Convert.ToInt32(ItemValues.GetValue(i));
                        break;
                    case 13:
                        ProductRunningFlag = Convert.ToBoolean(ItemValues.GetValue(i));
                        break;
                    case 14:
                        IsOK = Convert.ToBoolean(ItemValues.GetValue(i));
                        break;
                    case 15:
                        IsNG = Convert.ToBoolean(ItemValues.GetValue(i));
                        break;
                    case 16:
                        Max = Convert.ToInt32(ItemValues.GetValue(i));
                        break;
                    case 17:
                        Min = Convert.ToInt32(ItemValues.GetValue(i));
                        break;
                    default:
                        break;
                }
            }
            stopwatch.Stop();
            logger.Debug($"耗时:{stopwatch.ElapsedMilliseconds}ms");
        }
       
      

        private void Log(string message)
        {
            LogItem logItem = new LogItem();
            logItem.Time = DateTime.Now;
            logItem.Context = message;
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                Logitems.Insert(0, logItem);
                if (Logitems.Count > 50)
                {
                    Logitems.RemoveAt(50);
                }
            }));
        
            logger.Info(message);
        }

        private void SettingLog(string message)
        {
            LogItem logItem = new LogItem();
            logItem.Time = DateTime.Now;
            logItem.Context = message;
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                Logitems.Insert(0, logItem);
                if (Logitems.Count > 50)
                {
                    Logitems.RemoveAt(50);
                }
            }));

            settinglogger.Info(message);
        }

        [RelayCommand]
        private void Save()
        {
            string jsonString =JsonConvert.SerializeObject(Products);
            File.WriteAllText("products.json", jsonString);
            MessageBox.Show($"产品信息保存成功：{jsonString}");
            SettingLog($"产品信息保存成功：{jsonString}");
        }

        [RelayCommand]
        private void SaveSettings()
        {
            string jsonString = JsonConvert.SerializeObject(Settings);
            File.WriteAllText("Settings.json", jsonString);
            MessageBox.Show($"系统设置保存成功：{jsonString}");
            SettingLog($"系统设置保存成功：{jsonString}");
        }

        [RelayCommand]
        private void Add()
        {
            Products?.Add(new Product() { Name ="空白"});
        }
        [RelayCommand]
        private void Remove()
        {
            if (Products?.Count > 0)
            {
                Products.RemoveAt(Products.Count-1);
            }
        }
        

        [RelayCommand]
        private void DataQuery()
        {
             //MessageBox.Show(SelectedQueryName);
            //logger.Info($"{NameChecked},{NameText};;{StartTimeChecked},{StartTime.ToString()};;{StopTimeChecked},{StopTime.ToString()};{CodeChecked},{CodeText}");
            try
            {
                Log($"数据查询开始");
                var query = SqlSugarHelper.Db.Queryable<Record>();
                if (NameChecked)
                    query.Where(it => it.ProductName == SelectedQueryName);
                if (StartTimeChecked)
                    query.Where(it => it.DateTime >= StartTime);
                if (StopTimeChecked)
                    query.Where(it => it.DateTime <= StopTime);
                if (CodeChecked)
                    query.Where(it => it.ProductCode.Contains(CodeText));
               
                DataLists = query.Clone().ToList();
               // Log($"{NameChecked.ToString()},{selectedQueryName}");
                Log($"数据查询成功，查询到{DataLists?.Count} records");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }
        [RelayCommand]
        private void ExportExcel()
        {
            try
            {
                string path = Directory.GetCurrentDirectory() + "\\Output\\";
                if(!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                path = Path.Combine(path, $"{Guid.NewGuid()}.xlsx");
                MiniExcel.SaveAs(path, DataLists);
                MessageBox.Show("数据导出成功");
                Log("数据导出成功");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }

        [RelayCommand]
        private async Task DataUpdate()
        {
            if (SelectedRecord == null)
            {
                MessageBox.Show("请选择一条数据");
                return;
            }
            if(MessageBox.Show($"是否对选中的数据进行手动报工,二维码：{SelectedRecord?.ProductCode}","提示",MessageBoxButton.OKCancel)==MessageBoxResult.OK)
            {
                ReportWorkMessage reportWorkMessage = new ReportWorkMessage();
                reportWorkMessage.EquipmentCode = SelectedRecord.EquipmentCode;
                reportWorkMessage.TaskId = SelectedRecord.ProdTaskId;
                reportWorkMessage.UserId = Settings.UserId;
                reportWorkMessage.ProductSerialNumberInfoList = new List<ProductSerialNumberInfoList>();
                ProductSerialNumberInfoList productSerialNumberInfoList = new ProductSerialNumberInfoList();
                productSerialNumberInfoList.ProductSerialNumber = SelectedRecord.ProductCode;
                productSerialNumberInfoList.Result = SelectedRecord.Result;
                productSerialNumberInfoList.Ext = JsonConvert.SerializeObject(SelectedRecord.Content);
                reportWorkMessage.ProductSerialNumberInfoList.Add(productSerialNumberInfoList);

                var jsonreport = JsonConvert.SerializeObject(reportWorkMessage);
                Log($"报工发送数据：{jsonreport}");
                try
                {
                    var result = await SendHttpPostAsync(Settings.UrlReportWork, jsonreport);
                    if (result != null)
                    {

                        Log($"报工返回结果：{result}");
                        var reportWorkResult = JsonConvert.DeserializeObject<RecvMaterialMessage>(result);
                        if (reportWorkResult != null && reportWorkResult.Data != null && reportWorkResult.Data[0].Success == true)
                        {
                            Log($"报工成功：{reportWorkResult.Data[0].Msg}");
                        }
                        else
                        {
                            Log($"报工失败：{reportWorkResult?.Data?[0].Msg}");
                        }
                    }
                    else
                    {
                        Log("报工返回数据为空");
                    }
                }
                catch (Exception ex)
                {
                    Log($"报工数据发送失败：{ex.Message}");
                }
            }

        }

        [RelayCommand(CanExecute =nameof(IsTaskQuery))]
       
        private async Task TaskQuery()
        {
            //HttpClient httpClient = new HttpClient();
            
            try
            {
                string url = $"{Settings.UrlGetTask}?equipmentCode={Settings.EquipmentCode}&userId={Settings.UserId}&productCode={selectedProduct?.MaterialCode}";
                //string url = $"{Settings.UrlGetTask}?equipmentCode={Settings.EquipmentCode}&userId={Settings.UserId}&productCode=01040204-00172";
                //var response = httpClient.GetAsync(url).Result;
                //if (response.IsSuccessStatusCode)
                //{
                //    var content = response.Content.ReadAsStringAsync().Result;
                //    //MessageBox.Show(content);
                //    var result = JsonConvert.DeserializeObject<RecvTaskDetail>(content);
                //    if (result?.Data?.Count > 0)
                //    {
                //        TaskInfos.Clear();
                //        foreach(var item in result.Data)
                //        {
                //            TaskInfos.Add(item);
                //        }
                //        //MessageBox.Show($"工单查询成功，共{result.Data.Count}条");
                //        Log($"工单查询成功，共{result.Data.Count}条");
                //    }
                //    else
                //    {
                //        MessageBox.Show("工单查询失败，工单列表为空");
                //        Log("工单查询失败，工单列表为空");
                //    }
                //}
                //else
                //{
                //    MessageBox.Show("工单查询失败：" + response.StatusCode);
                //    Log("工单查询失败：" + response.StatusCode);
                //}
                string jsonresult = await SendHttpRequestAsync(url);
                if (jsonresult != null)
                {
                    var result = JsonConvert.DeserializeObject<RecvTaskDetail>(jsonresult);
                    if(result?.Data?.Count > 0)
                    {
                        TaskInfos.Clear();
                        foreach(var item in result.Data)
                        {
                            TaskInfos.Add(item);
                        }
                        Log($"工单查询成功，共{result.Data.Count}条");
                    }
                    else
                    {
                        MessageBox.Show("工单查询失败，工单列表为空");
                        Log("工单查询失败，工单列表为空");
                    }
                }


            }
            catch(Exception ex)
            {
                MessageBox.Show("工单查询失败：" + ex.Message);
                logger.Error(ex.Message);
            }

        }
        /// <summary>
        /// 发送HTTP请求并返回响应内容
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private async Task<string> SendHttpRequestAsync(string str)
        {
            // 创建HttpClient实例
            using (HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(3) })
            {
                try
                {
                    // 发送异步GET请求并等待响应
                    HttpResponseMessage response = await client.GetAsync(str);

                    // 确保响应成功
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容并等待内容的读取
                    string content = await response.Content.ReadAsStringAsync();

                    // 返回响应内容
                    return content;
                }
                catch(Exception ex)
                {
                    throw new Exception( ex.Message);
                }
            }
        }
        /// <summary>
        /// 发送HTTP POST请求并返回响应内容
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonBody"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private async Task<string> SendHttpPostAsync(string url,string jsonBody)
        {
            using (HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(3) })
            {
                try
                {
                    var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();
                    string responsebody = await response.Content.ReadAsStringAsync();
                    return responsebody;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
    }
   
}
